package com.laicunba.event.listener;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.laicunba.event.UserCreateEvent;
import com.laicunba.pojo.UserDO;
import com.laicunba.pojo.UserPackageItemDO;
import com.laicunba.service.RegistryService;
import com.laicunba.service.UserPackageItemService;
import com.laicunba.util.LogUtil;
import com.laicunba.util.StringUtil;

/**
 * 发放注册用户福利
 * 
 * @author why
 *
 */
public class GrantUserCreatePackageListener implements ApplicationListener<UserCreateEvent> {
	private static final Logger LOG = Logger.getLogger(GrantUserCreatePackageListener.class);
	@Autowired
	private UserPackageItemService userPackageItemService;
	@Autowired
	private RegistryService registryService;

	@Override
	public void onApplicationEvent(UserCreateEvent event) {
		if (event.getSource() == null) {
			return;
		}
		UserDO userDO = (UserDO) event.getSource();
		if(userDO==null){
			return;
		}
		if(StringUtil.isNotEmpty(userDO.getChannel())&&userDO.getChannel().startsWith("no-award")){
			return;
		}
		
		Map<String, String> map = registryService.likeKey("act.regist.");
		if (!"true".equalsIgnoreCase(map.get("act.regist.open"))) {
			return;
		}
		String amount = map.get("act.regist.amount");
		String name = map.get("act.regist.name");
		String summary = map.get("act.regist.summary");
		if (!StringUtil.isNumber(amount) || StringUtil.isEmpty(name, summary)) {
			LOG.warn("注册活动已开启,但配置信息不全(或有错),放弃活动内容!");
			return;
		}
		UserPackageItemDO item = new UserPackageItemDO();
		item.setUsed(false);
		item.setBeginTime(new Date());
		Date endTime = new Date();
		endTime.setDate(endTime.getDate() + 10);
		item.setEndTime(endTime);
		item.setAmount(BigDecimal.valueOf(Long.parseLong(amount)));
		item.setType("ACT_REGIST");
		item.setName(name);
		item.setSummary(summary);
		item.setUserId(((UserDO) event.getSource()).getId());
		if (userPackageItemService.create(item)) {
			LOG.info(LogUtil.format("TAG:GRANT_USER_CREATE_PACKAGE", String.format("给%s发放%s元体验金红色", item.getId(), item.getAmount())));
		} else {
			LOG.error(LogUtil.format("TAG:GRANT_USER_CREATE_PACKAGE_ERROR", null));
		}
	}

}
